import React, { Component } from 'react'
import BaseImageUp from '../base'
import { upImage } from '../../../ajax/axios'
import { Api } from '../../../ajax/api'
import { message } from 'antd';

interface StateInterface {
  localImg?: string
}

interface PropsInterface {
  souceImg?: string
}

export interface UpFileResultInterface {
  encoding: string
  field: string
  fieldname: string
  filename: string
  filepath: string
  mime: string
  mimeType: string
  serverPath: string
  transferEncoding: string
}

export default class ComUpImageEcs extends Component<PropsInterface, StateInterface> {

  file?: File

  state: Readonly<StateInterface> = {

  }

  constructor(props: PropsInterface) {
    super(props)

    this.fileChange = this.fileChange.bind(this)
  }

  fileChange(file: File, localImg: string) {
    this.file = file
    this.setState(() => {
      return {
        localImg
      }
    })
  }

  async upImage(require = true): Promise<UpFileResultInterface> {
    if (this.file) {
      const data = await upImage(Api.server.imageUp, 'file', this.file)
      this.setState(() => {
        return {
          localImg: undefined
        }
      })
      this.file = undefined
      return data as any
    } else {
      if (require) {
        message.error('请选择图片')
      }
      throw Error('未选择图片')
    }
  }

  render(): React.ReactElement<any, string | React.JSXElementConstructor<any>> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
    return <BaseImageUp onChange={this.fileChange} imgData={ this.state.localImg || this.props.souceImg }></BaseImageUp>
  }
}